package com.shop.cereshop.app.controller.tencent.moderation;

import com.shop.cereshop.app.tencent.moderation.domain.VideoModerationCallbackRequest;
import com.shop.cereshop.app.tencent.moderation.domain.VideoModerationCallbackResponse;
import com.shop.cereshop.app.tencent.moderation.service.VideoModerationCallbackService;
import com.shop.cereshop.commons.tencent.moderation.domain.request.CreateVideoModerationTaskParam;
import com.shop.cereshop.commons.tencent.moderation.domain.request.ImageModerationParam;
import com.shop.cereshop.commons.tencent.moderation.domain.response.VideoModerationResult;
import com.shop.cereshop.commons.tencent.moderation.service.ImageModerationService;
import com.shop.cereshop.commons.tencent.moderation.service.TextModerationService;
import com.shop.cereshop.commons.tencent.moderation.domain.request.TextModerationParam;
import com.shop.cereshop.commons.tencent.moderation.domain.response.ModerationResult;
import com.shop.cereshop.commons.tencent.moderation.service.VideoModerationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @description: 腾讯云内容审核接口
 * @author zdd
 * @date 2025/10/27 0:25
 * @version 1.0
 */
@Validated
@RestController
@RequestMapping("/moderation")
@Slf4j(topic = "TencentModerationController")
@Api(value = "腾讯内容审核接口", tags = "腾讯内容审核接口")
public class TencentModerationController {

    @Autowired
    private TextModerationService textModerationService;
    @Autowired
    private ImageModerationService imageModerationService;
    @Autowired
    private VideoModerationService videoModerationService;
    @Autowired
    private VideoModerationCallbackService videoCallbackService;

    @ApiOperation(value = "审核单个文本")
    @PostMapping("/text/single")
    public ModerationResult moderateText(@Valid @RequestBody TextModerationParam request) {
        log.info("收到文本审核请求, contentLength: {},  content: {}", request.getContent().length(), request.getContent());
        return textModerationService.moderateText(request);
    }

    @ApiOperation(value = "批量审核文本")
    @PostMapping("/text/batch")
    public List<ModerationResult> batchModerateText(@Valid @RequestBody List<TextModerationParam> requests) {
        log.info("收到批量文本审核请求, count: {}", requests.size());
        return textModerationService.batchModerateText(requests);
    }

    @ApiOperation(value = "审核单个图片")
    @PostMapping("/image/single")
    public ModerationResult moderateImage(@Valid @RequestBody ImageModerationParam request) {
        log.info("收到图片审核请求");
        return imageModerationService.moderateImage(request);
    }

    @ApiOperation(value = "批量审核图片")
    @PostMapping("/image/batch")
    public List<ModerationResult> batchModerateImages(@Valid @RequestBody List<ImageModerationParam> requests) {
        log.info("收到批量图片审核请求, count: {}", requests.size());
        return imageModerationService.batchModerateImages(requests);
    }

    @ApiOperation(value = "创建视频审核任务")
    @PostMapping("/video/task")
    public VideoModerationResult createTask(@Valid @RequestBody CreateVideoModerationTaskParam request) {
        log.info("创建视频审核任务, videoUrl: {}", request.getVideoUrl());
        return videoModerationService.createModerationTask(request);
    }

    @ApiOperation(value = "查询视频审核任务结果")
    @GetMapping("/video/task/{taskId}")
    public VideoModerationResult getTaskResult(@PathVariable String taskId) {
        log.info("查询视频审核任务结果, taskId: {}", taskId);
        return videoModerationService.getTaskResult(taskId);
    }

    @ApiOperation(value = "取消视频审核任务")
    @DeleteMapping("/video/task/{taskId}")
    public String cancelTask(@PathVariable String taskId) {
        log.info("取消视频审核任务, taskId: {}", taskId);
        boolean success = videoModerationService.cancelTask(taskId);
        return success ? "取消成功" : "取消失败";
    }

    /**
     * 视频审核结果回调接口
     * POST /moderation/video/callback
     * 腾讯云会在视频审核完成后调用此接口
     */
    @ApiOperation(value = "视频审核结果回调接口")
    @PostMapping("/video/callback")
    public VideoModerationCallbackResponse handleVideoModerationCallback(
            @RequestBody VideoModerationCallbackRequest request,
            HttpServletRequest httpRequest) {

        // 记录原始请求信息（用于调试）
        log.debug("收到回调请求, RemoteAddr: {}, ContentType: {}",
                httpRequest.getRemoteAddr(),
                httpRequest.getContentType());

        // 可选：验证签名
        String signature = httpRequest.getHeader("Signature");
        String timestamp = httpRequest.getHeader("Timestamp");
        String nonce = httpRequest.getHeader("Nonce");

        if (signature != null && timestamp != null && nonce != null) {
            boolean valid = videoCallbackService.verifySignature(signature, timestamp, nonce,
                    httpRequest.getParameter("body"));
            if (!valid) {
                log.error("回调签名验证失败");
                return VideoModerationCallbackResponse.fail("Signature verification failed");
            }
        }

        // 处理回调
        return videoCallbackService.handleCallback(request);
    }

}
